package com.demon.mutehelper.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.demon.mutehelper.bean.MuteRecord
import com.demon.mutehelper.database.AppDatabase
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

class MuteRecordEditViewModel(application: Application, val recordId: Int) :
  AndroidViewModel(application) {
  private val database = AppDatabase.getDatabase(application)
  private val _recordFlow = MutableStateFlow(MuteRecord())
  val recordFlow: StateFlow<MuteRecord> = _recordFlow
  private val _uiStateFlow = MutableSharedFlow<UIState>()
  val uiStateFlow: SharedFlow<UIState> = _uiStateFlow

  init {
    if (recordId >= 0) {
      viewModelScope.launch(Dispatchers.IO) {
        database.muteRecordDao().getRecordById(recordId).collectLatest {
          _recordFlow.emit(it)
        }
      }
    }
  }

  fun delete() {
    viewModelScope.launch(Dispatchers.IO) {
      database.muteRecordDao().deleteRecord(recordFlow.value)
      _uiStateFlow.emit(UIState.Success)
    }
  }

  fun save() {
    viewModelScope.launch(Dispatchers.IO) {
      database.muteRecordDao().insertOrUpdateRecord(recordFlow.value)
      _uiStateFlow.emit(UIState.Success)
    }

  }

  fun updateName(name: CharSequence) {
    recordFlow.value.name = name.toString()
  }

  fun updateStartTime(startTime: Long) {
    recordFlow.value.startTime = startTime
  }

  fun updateLocation(address: String?, lat: Double?, lon: Double?) {
    recordFlow.value.apply {
      this.address = address
      this.lat = lat
      this.lon = lon
    }
  }

  class MuteRecordEditViewModelFactory(
    private val application: Application,
    private val recordId: Int
  ) : ViewModelProvider.Factory {
    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
      return MuteRecordEditViewModel(application, recordId) as T
    }

  }

  sealed class UIState {
    object Success : UIState()
    object Failed : UIState()
  }
}